/**
 * Created by denh on 16/12/14.
 */
(function(win,doc){
    function change(){
        doc.documentElement.style.fontSize=doc.documentElement.clientWidth/375*23.4375+'px';
    }
    change();
    win.addEventListener('resize',change,false);
})(window,document);

window.scrollH = [];
var isClickHistory = false;



token = '<?=$this->token?>';
userId = '<?=$this->accout?>';

var appKey = '611d56bcd17bdfa4a83e5bdf55916589';
var chatId = common.getParam('chatId');
var chatroomObj; //
var timeStamp = new Date().getTime();

var msgReturnNum; //单次实际返回消息数
var msgGetNum = 50; //单次获取历史消息数
var msgCountPerFlush = 0; //每次刷新返回的消息数
var userStatus = -1; //是否是认证用户,true为已认证用户

//for(var key in  emoji){
    //emoji[key].fFile='inputEmojiCon.png';
   // console.log(emoji[key].file);
//}


v_foot = new Vue({
    el : '#foot',
    data : {
        text : '',
        emojis : [],
        isEmojiShow : false,
        sDisable : false,
        placeholdertext : ""
    },
    methods : {
        showEmoji : function () {
            //for(var key in  emoji){
                //emoji[key].fFile=emoji[key].file;
            //}
            this.emojis = emoji;

            this.isEmojiShow = !this.isEmojiShow;
        },

        selectEmoji : function (v) {
            this.text += v;
            this.isEmojiShow = false;
        },

        sendMessage : function () {
            var text = this.text;
            if (this.text.length <= 0) {
                return;
            }
            var msg = chatroomObj.sendText({
                text: text,
                done: sendChatroomMsgDone
            });
        }
    }
});



v_chat = new Vue({
    el : '#content',
    data : {
        msgs : []
    }
});

var nim = NIM.getInstance({
    debug: false,
    appKey: appKey,
    account: userId,
    token: token,
    onconnect: onConnect
});


function onConnect() {
    console.log('连接成功');
    nim.getChatroomAddress({
        chatroomId: chatId,
        done: getChatroomAddressDone
    });
}

function getChatroomAddressDone(error, obj) {
    console.log('获取聊天室地址' + (!error?'成功':'失败'), error, obj);
    if(!error){
        chatroomObj = Chatroom.getInstance({
            appKey: appKey,
            account: userId,
            token: token,
            chatroomId: chatId,
            chatroomAddresses: obj.address,
            onconnect: onChatroomConnect,
            //onerror: onChatroomError,
            //onwillreconnect: onChatroomWillReconnect,
            //ondisconnect: onChatroomDisconnect,
            // 消息
            onmsgs: onChatroomMsgs
        });
    }
}

function onChatroomConnect(chatroom) {
    console.log('进入聊天室', chatroom);
    getHistoryMsgs(timeStamp);
}

//获取历史消息
function getHistoryMsgsDone(error, obj) {
    console.log('获取聊天室历史' + (!error?'成功':'失败'), error, obj.msgs);
    msgReturnNum = obj.msgs.length;
    if(!error && obj.msgs.length > 0){
        for(var i=0;i<obj.msgs.length;i++) {
            var msg = obj.msgs[i];
            timeStamp = msg.time;

            //msg.type == 'image' || msg.type == 'audio'
            if (msg.type == 'text') {
                msg = formatMsg(msg);
                msgCountPerFlush++;
                v_chat.msgs.unshift(msg);
            }
        }

        if(msgReturnNum == msgGetNum && msgCountPerFlush < 10){
            chatroomObj.getHistoryMsgs({
                timetag: timeStamp,  //不填表示当前时间戳
                limit: msgGetNum,
                done: getHistoryMsgsDone
            });
        }else{
            footerfunction();
        }

    }
}

//从自己的服务接口获取历史消息
    function getHistoryMsgs(time) {
        var hproseUrl = "http://necallback.babydr.cn/necallback/hprose";
        hproseMethods = [
            'MsgController_msgList'
        ];
        var hproseClient = hprose.Client.create(hproseUrl, hproseMethods);
        hproseClient.MsgController_msgList(chatId, time, function(result) {
            var formatMsgArr = [];
            for (i=0; i<result.result.length; i++) {
                tmsg = eval('('+ result.result[i] +')');
                msg = {};
                msg.type = tmsg.msgType;
                msg.fromAvatar = tmsg.fromAvator;
                msg.fromNick = tmsg.fromNick;
                msg.from = tmsg.fromAccount;
                msg.idClient = tmsg.msgidClient;
                msg.time = tmsg.msgTimestamp;
                timeStamp = msg.time;

                if (tmsg.msgType == 'TEXT') {
                    msg.text = tmsg.attach;
                    msg.type = 'text';
                } else if (tmsg.msgType == 'PICTURE') {
                    msg.file = eval('('+ tmsg.attach +')');
                    msg.type = 'image';
                }

                formatMsgArr.unshift(formatMsg(msg));
            }
            v_chat.msgs = formatMsgArr.concat(v_chat.msgs);
            $("#content").scrollTop($("#content")[0].scrollHeight - window.scrollH[window.scrollH.length-2]);
            console.log($("#content")[0].scrollHeight);
            $(".freChat").hide();
            if (isClickHistory == false) {
                window.scrollH.push($("#content")[0].scrollHeight);
                footerfunction();
            }

        });
    }

//查看历史消息
    $("#content").scroll(function(){
        if($("#content").scrollTop() == 0){
            window.scrollH.push($("#content")[0].scrollHeight);
            console.log(window.scrollH);
            isClickHistory = true;
            $(".freChat").show();
            if ($("#content").scrollTop() <= 0) {
                getHistoryMsgs(timeStamp);
            }
        }
    });

    //收到聊天室消息
    function onChatroomMsgs(msgs) {
        var msg = msgs[0];
        if (msg.type == 'text') {
            msg = formatMsg(msg);
            v_chat.msgs.push(msg);
            footerfunction();
        }
        console.log('收到聊天室消息', msgs);
    }

    function sendChatroomMsgDone(error, msg) {
        console.log('发送聊天室' + msg.type + '消息' + (!error?'成功':'失败') + ', id=' + msg.idClient, error, msg);
        if(!error){
            msg = formatMsg(msg);
            v_chat.msgs.push(msg);
            v_foot.text = '';
            footerfunction();
        }
    }

    function formatMsg(msg) {
        msg.isLeft = false;
        msg.isRight = false;
        if (msg.from == userId) {
            msg.isRight = true;
        } else {
            msg.isLeft = true;
        }

        msg.text = common.html_encode(msg.text);
        msg.text =  buildEmoji(msg.text);
        return msg;
    }

    //
    function footerfunction(){
        Vue.nextTick(function(){
            $("#content")[0].scrollTop = $("#content")[0].scrollHeight;
        });
    }

    $(document).scroll(function(){
        if($(document)[0].body.scrollTop == 0) {
            chatroomObj.getHistoryMsgs({
                timetag: timeStamp,  //不填表示当前时间戳
                limit: msgGetNum,
                done: getHistoryMsgsDone
            });
        }
    });




//在非WiFi环境下提示
wx.ready(function(){
    wx.getNetworkType({
        success: function (res) {
            var networkType = res.networkType; // 返回网络类型2g，3g，4g，wifi
            if (networkType != 'wifi') {
                $("#header").show();
            }
        }
    });
});

$(function(){
    // 文本输入框的宽度
    var sendwidth = $(".entering").width() - $(".send").outerWidth(true) - $(".emoji").outerWidth(true)-2 ;
    $(".entering .enteringInput").css("width", sendwidth);
    $("#content").height($(window).height()-$(".entering").outerHeight(true));
});





